package com.xy.service.impl;

import com.xy.entity.User;
import com.xy.repository.UserRepository;
import com.xy.service.AuthService;
import com.xy.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

/**
 * Created by Thinkpad on 2018/1/7.
 */
@Service
public class AuthServiceImpl implements AuthService {

    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;
    private JwtTokenUtil jwtTokenUtil;
    private UserRepository userRepository;
    private BCryptPasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    public AuthServiceImpl(
            AuthenticationManager authenticationManager,
            UserDetailsService userDetailsService,
            JwtTokenUtil jwtTokenUtil,
            UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public User login(String username, String password) {

        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        // Perform the security
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        User sysUser = (User) userDetailsService.loadUserByUsername(username);
        String token = jwtTokenUtil.generateToken(sysUser);
        sysUser.setCurrentToken(token);
        return sysUser;
    }

    @Override
    public User login(String username) {
        User sysUser = new User();
        try {
            sysUser = (User) userDetailsService.loadUserByUsername(username);
        } catch (Exception e) {
            if(e.getMessage().equals("用户名不存在")){
                User user = new User();
                user.setUsername(username);
                user.setPhone(username);
                sysUser = userRepository.save(user);
            }
        }

        String token = jwtTokenUtil.generateToken(sysUser);
        sysUser.setCurrentToken(token);
        return sysUser;
    }

    @Override
    public User register(User userToAdd) {
        final String username = userToAdd.getUsername();
        if (userRepository.findByUsername(username) != null) {
            return null;
        }

        final String rawPassword = userToAdd.getPassword();
        userToAdd.setPassword(passwordEncoder.encode(rawPassword));
        userToAdd.setLastPasswordResetDate(new Date());
        userToAdd.setPhone(username);
//        userToAdd.setRoles(Arrays.asList("ROLE_USER"));
        return userRepository.save(userToAdd);
    }
}
